package service

import (
	"context"
	"fmt"
	"gitee.com/crack007/goose"
	"github.com/crack007/go-im/src/common/constant"
	"github.com/crack007/go-im/src/common/model"
	"github.com/crack007/go-im/src/common/service"
	"github.com/crack007/go-im/src/module/api/dto"
	"sync"
)

type apiService struct {
	lock sync.Mutex
}

func (s *apiService) Bootstrap(ctx context.Context) {
	etcdService := service.EtcdService
	etcdService.Init(ctx)
	etcdService.ListNode(constant.NodePath, func(etcdModel *model.EtcdModel) {
		service.NodeService.Add(etcdModel.Node)
	})
	etcdService.Watch(constant.NodePath, func(nodeName string, event string, etcdModel *model.EtcdModel) {
		if event == "DELETE" {
			goose.GetLogger().Info("offline-> %s", nodeName)
			service.NodeService.Remove(nodeName)
		}
		if event == "PUT" {
			goose.GetLogger().Info("online-> %s", etcdModel)
			service.NodeService.Add(etcdModel.Node)
		}
	})
}

func (s *apiService) ListNode() *dto.WsNodeDto {
	wsNodeDto := &dto.WsNodeDto{}
	list := service.NodeService.List()
	if len(list) > 0 {
		for _, v := range list {
			wsNodeDto.Node = append(wsNodeDto.Node, fmt.Sprintf("%s:%d", v.Ip, v.WsPort))
		}
	}
	return wsNodeDto
}
